<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="人员A" prop="memberNameA">
        <el-input
          v-model="queryParams.memberNameA"
          placeholder="请输入人员A姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="人员B" prop="memberNameB">
        <el-input
          v-model="queryParams.memberNameB"
          placeholder="请输入人员B姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="匹配类型" prop="matchType">
        <el-select v-model="queryParams.matchType" placeholder="请选择匹配类型" clearable>
          <el-option label="自动匹配" value="AUTO" />
          <el-option label="手动匹配" value="MANUAL" />
        </el-select>
      </el-form-item>
      <el-form-item label="匹配状态" prop="matchStatus">
        <el-select v-model="queryParams.matchStatus" placeholder="请选择匹配状态" clearable>
          <el-option
            v-for="dict in dict.type.dating_match_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="匹配结果" prop="matchResult">
        <el-select v-model="queryParams.matchResult" placeholder="请选择匹配结果" clearable>
          <el-option
            v-for="dict in dict.type.dating_match_result"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['dating:match:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-connection"
          size="mini"
          @click="handleAutoMatch"
          v-hasPermi="['dating:match:auto']"
        >自动匹配</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-s-data"
          size="mini"
          @click="handleStatistics"
        >匹配统计</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['dating:match:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['dating:match:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="matchList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="匹配ID" align="center" prop="matchId" />
      <el-table-column label="人员A" align="center" prop="memberNameA" />
      <el-table-column label="人员B" align="center" prop="memberNameB" />
      <el-table-column label="匹配得分" align="center" prop="matchScore">
        <template slot-scope="scope">
          <el-progress 
            :percentage="parseFloat(scope.row.matchScore)" 
            :color="getScoreColor(scope.row.matchScore)"
            :format="format => format + '分'"
          ></el-progress>
        </template>
      </el-table-column>
      <el-table-column label="匹配类型" align="center" prop="matchType">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.matchType === 'AUTO'" type="primary">自动匹配</el-tag>
          <el-tag v-else type="warning">手动匹配</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="匹配状态" align="center" prop="matchStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.dating_match_status" :value="scope.row.matchStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="A方联系状态" align="center" prop="contactStatusA">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.dating_contact_status" :value="scope.row.contactStatusA"/>
        </template>
      </el-table-column>
      <el-table-column label="B方联系状态" align="center" prop="contactStatusB">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.dating_contact_status" :value="scope.row.contactStatusB"/>
        </template>
      </el-table-column>
      <el-table-column label="匹配结果" align="center" prop="matchResult">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.dating_match_result" :value="scope.row.matchResult"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['dating:match:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['dating:match:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改婚恋匹配记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="人员A ID" prop="memberIdA">
          <el-input v-model="form.memberIdA" placeholder="请输入人员A ID" />
        </el-form-item>
        <el-form-item label="人员B ID" prop="memberIdB">
          <el-input v-model="form.memberIdB" placeholder="请输入人员B ID" />
        </el-form-item>
        <el-form-item label="匹配类型" prop="matchType">
          <el-select v-model="form.matchType" placeholder="请选择匹配类型">
            <el-option label="自动匹配" value="AUTO" />
            <el-option label="手动匹配" value="MANUAL" />
          </el-select>
        </el-form-item>
        <el-form-item label="匹配状态" prop="matchStatus">
          <el-select v-model="form.matchStatus" placeholder="请选择匹配状态">
            <el-option
              v-for="dict in dict.type.dating_match_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="A方联系状态" prop="contactStatusA">
          <el-select v-model="form.contactStatusA" placeholder="请选择A方联系状态">
            <el-option
              v-for="dict in dict.type.dating_contact_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="B方联系状态" prop="contactStatusB">
          <el-select v-model="form.contactStatusB" placeholder="请选择B方联系状态">
            <el-option
              v-for="dict in dict.type.dating_contact_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="A方反馈" prop="feedbackA">
          <el-input v-model="form.feedbackA" type="textarea" placeholder="请输入A方反馈" />
        </el-form-item>
        <el-form-item label="B方反馈" prop="feedbackB">
          <el-input v-model="form.feedbackB" type="textarea" placeholder="请输入B方反馈" />
        </el-form-item>
        <el-form-item label="匹配结果" prop="matchResult">
          <el-select v-model="form.matchResult" placeholder="请选择匹配结果">
            <el-option
              v-for="dict in dict.type.dating_match_result"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="成功配对日期" prop="successDate" v-if="form.matchResult === 'SUCCESS'">
          <el-date-picker clearable
            v-model="form.successDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择成功配对日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 自动匹配对话框 -->
    <el-dialog title="自动匹配" :visible.sync="autoMatchOpen" width="600px" append-to-body>
      <el-form ref="autoMatchForm" :model="autoMatchForm" label-width="120px">
        <el-form-item label="选择人员" prop="memberId" required>
          <el-select v-model="autoMatchForm.memberId" placeholder="请选择要匹配的人员" filterable>
            <el-option
              v-for="member in memberOptions"
              :key="member.memberId"
              :label="member.realName + ' (' + member.memberNo + ')'"
              :value="member.memberId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="匹配数量" prop="maxCount">
          <el-input-number v-model="autoMatchForm.maxCount" :min="1" :max="10" controls-position="right"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAutoMatch" :loading="autoMatchLoading">开始匹配</el-button>
        <el-button @click="autoMatchOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 匹配统计对话框 -->
    <el-dialog title="匹配统计" :visible.sync="statisticsOpen" width="800px" append-to-body>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card>
            <div slot="header">总匹配数</div>
            <div class="statistic-value">{{ statistics.totalMatches || 0 }}</div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card>
            <div slot="header">成功匹配数</div>
            <div class="statistic-value">{{ statistics.successMatches || 0 }}</div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card>
            <div slot="header">成功率</div>
            <div class="statistic-value">{{ statistics.successRate || '0.00%' }}</div>
          </el-card>
        </el-col>
      </el-row>
      <el-divider>各状态统计</el-divider>
      <el-table :data="statusStatsData" style="width: 100%">
        <el-table-column prop="status" label="状态" align="center" />
        <el-table-column prop="count" label="数量" align="center" />
        <el-table-column prop="percentage" label="占比" align="center" />
      </el-table>
    </el-dialog>

    <!-- 匹配详情对话框 -->
    <el-dialog title="匹配详情" :visible.sync="detailOpen" width="900px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="匹配ID">{{ detailData.matchId }}</el-descriptions-item>
        <el-descriptions-item label="匹配得分">{{ detailData.matchScore }}分</el-descriptions-item>
        <el-descriptions-item label="人员A">{{ detailData.memberNameA }}</el-descriptions-item>
        <el-descriptions-item label="人员B">{{ detailData.memberNameB }}</el-descriptions-item>
        <el-descriptions-item label="匹配类型">
          <el-tag v-if="detailData.matchType === 'AUTO'" type="primary">自动匹配</el-tag>
          <el-tag v-else type="warning">手动匹配</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="匹配状态">
          <dict-tag :options="dict.type.dating_match_status" :value="detailData.matchStatus"/>
        </el-descriptions-item>
        <el-descriptions-item label="A方联系状态">
          <dict-tag :options="dict.type.dating_contact_status" :value="detailData.contactStatusA"/>
        </el-descriptions-item>
        <el-descriptions-item label="B方联系状态">
          <dict-tag :options="dict.type.dating_contact_status" :value="detailData.contactStatusB"/>
        </el-descriptions-item>
        <el-descriptions-item label="匹配结果">
          <dict-tag :options="dict.type.dating_match_result" :value="detailData.matchResult"/>
        </el-descriptions-item>
        <el-descriptions-item label="成功配对日期">{{ parseTime(detailData.successDate, '{y}-{m}-{d}') }}</el-descriptions-item>
        <el-descriptions-item label="A方反馈" :span="2">{{ detailData.feedbackA }}</el-descriptions-item>
        <el-descriptions-item label="B方反馈" :span="2">{{ detailData.feedbackB }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detailData.remark }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(detailData.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ parseTime(detailData.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import { listMatch, getMatch, delMatch, addMatch, updateMatch, autoMatch, getMatchStatistics } from "@/api/dating/match";
import { listMember } from "@/api/dating/member";

export default {
  name: "Match",
  dicts: ['dating_match_status', 'dating_contact_status', 'dating_match_result'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 婚恋匹配记录表格数据
      matchList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 自动匹配对话框
      autoMatchOpen: false,
      autoMatchLoading: false,
      // 统计对话框
      statisticsOpen: false,
      // 详情对话框
      detailOpen: false,
      detailData: {},
      // 统计数据
      statistics: {},
      statusStatsData: [],
      // 人员选项
      memberOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        memberNameA: null,
        memberNameB: null,
        matchType: null,
        matchStatus: null,
        matchResult: null
      },
      // 表单参数
      form: {},
      // 自动匹配表单
      autoMatchForm: {
        memberId: null,
        maxCount: 5
      },
      // 表单校验
      rules: {
        memberIdA: [
          { required: true, message: "人员A ID不能为空", trigger: "blur" }
        ],
        memberIdB: [
          { required: true, message: "人员B ID不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getMemberOptions();
  },
  methods: {
    /** 查询婚恋匹配记录列表 */
    getList() {
      this.loading = true;
      listMatch(this.queryParams).then(response => {
        this.matchList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取人员选项 */
    getMemberOptions() {
      listMember({ pageNum: 1, pageSize: 1000, memberStatus: '1' }).then(response => {
        this.memberOptions = response.rows;
      });
    },
    /** 获取匹配得分颜色 */
    getScoreColor(score) {
      if (score >= 90) return '#67C23A';
      if (score >= 80) return '#E6A23C';
      if (score >= 70) return '#F56C6C';
      return '#909399';
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        matchId: null,
        memberIdA: null,
        memberIdB: null,
        matchScore: null,
        matchType: null,
        matchStatus: null,
        contactStatusA: null,
        contactStatusB: null,
        feedbackA: null,
        feedbackB: null,
        consultantId: null,
        matchResult: null,
        successDate: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.matchId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加婚恋匹配记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const matchId = row.matchId || this.ids
      getMatch(matchId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改婚恋匹配记录";
      });
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      this.detailData = row;
      this.detailOpen = true;
    },
    /** 自动匹配按钮操作 */
    handleAutoMatch() {
      this.autoMatchForm = {
        memberId: null,
        maxCount: 5
      };
      this.autoMatchOpen = true;
    },
    /** 提交自动匹配 */
    submitAutoMatch() {
      if (!this.autoMatchForm.memberId) {
        this.$modal.msgError("请选择要匹配的人员");
        return;
      }
      this.autoMatchLoading = true;
      autoMatch(this.autoMatchForm.memberId, this.autoMatchForm.maxCount).then(response => {
        this.$modal.msgSuccess(response.msg);
        this.autoMatchOpen = false;
        this.autoMatchLoading = false;
        this.getList();
      }).catch(() => {
        this.autoMatchLoading = false;
      });
    },
    /** 匹配统计按钮操作 */
    handleStatistics() {
      getMatchStatistics().then(response => {
        this.statistics = response.data;
        // 处理状态统计数据
        this.statusStatsData = [];
        if (response.data.statusStats) {
          const total = this.statistics.totalMatches || 1;
          for (const [status, count] of Object.entries(response.data.statusStats)) {
            this.statusStatsData.push({
              status: status,
              count: count,
              percentage: ((count / total) * 100).toFixed(2) + '%'
            });
          }
        }
        this.statisticsOpen = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.matchId != null) {
            updateMatch(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMatch(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const matchIds = row.matchId || this.ids;
      this.$confirm('是否确认删除婚恋匹配记录编号为"' + matchIds + '"的数据项？', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delMatch(matchIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('dating/match/export', {
        ...this.queryParams
      }, `match_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.statistic-value {
  font-size: 28px;
  font-weight: bold;
  color: #409EFF;
  text-align: center;
}
</style> 